#include "Socket_Server_T.hpp"
#include "SS_Client_T.hpp"
#include <arpa/inet.h>
#include <errno.h>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

SS_Client_T::SS_Client_T(Socket_Server_T& server, int socket_fd) :
   m_last_rcvd_msg_time(),
   m_msgs_recv(0),
   m_msgs_sent(0),
   m_outgoing_msg(NULL),
   m_outgoing_queue(),
   m_published_msg_codes(),
   m_recv_header_read(0),
   m_recv_header(),
   m_recv_payload_read(0),
   m_recv_payload(NULL),
   m_recv_total(0),
   m_send_header(),
   m_send_total(0),
   m_server(server),
   m_socket_fd(socket_fd),
   m_spied_from(),
   m_spied_to(),
   m_spy_from(),
   m_spy_to(),
   m_subscribed_msg_codes(),
   m_transmit_header_written(0),
   m_transmit_payload_size(0),
   m_transmit_payload_written(0),
   m_uid(0),
   m_client_description()
{

}

SS_Client_T::~SS_Client_T()
{
   SS_DBG(__FUNCTION__ << " (" << this << ") " << *this);

   Stop_Spying();

   Shutdown();

   free(m_recv_payload);

   while (!m_published_msg_codes.empty())
   {
      std::set<uint32_t>::iterator msg_code_it = m_published_msg_codes.begin();

      SS_DBG("Client had published message " << SS_Hex_Data_T(*msg_code_it));

      m_published_msg_codes.erase(msg_code_it);
   }

   m_server.Clean_Up_Client(m_uid);

   while (!m_subscribed_msg_codes.empty())
   {
      std::set<uint32_t>::iterator msg_code_it = m_subscribed_msg_codes.begin();
      Unsubscribe(*msg_code_it);
   }
   delete m_outgoing_msg;
   while (!m_outgoing_queue.empty())
   {
      delete m_outgoing_queue.front();
      m_outgoing_queue.pop();
   }
}



